<template>
  <div>
    <div class="header">
      <div class="fix-top" :style="{ backgroundColor: bgColor }">
        <div class="top-bg">
          <div class="left-box">
            <div class="logo">
              <img src="../assets/images/logoNew.png" alt="" width="40px" />
              <div class="name">E-base数字底座</div>
            </div>
            <ul class="nav">
              <li
                v-for="(item, index) in navList"
                :key="index"
                @click="goPage(item.path)"
                :class="active === index ? 'active' : ''"
              >
                {{ item.label }}
              </li>
              <li
                v-if="isLogin"
                @click="goPage('/setting')"
                :class="active === 6 ? 'active' : ''"
              >
                配置场景产品
              </li>
            </ul>
          </div>
          <div class="login-box" v-if="!isLogin">
            <i class="el-icon-user-solid f20"></i>
            <div
              class="mr10 ml10 pointer"
              @click=";(dialogFormVisible = true), checkLogin()"
            >
              登录
            </div>
          </div>

          <div class="login-box" v-if="isLogin">
            <i class="el-icon-user-solid f20"></i>
            <div class="mr10 ml10 pointer">{{ userInfo.name }}</div>
            |
            <div class="ml10 pointer" @click="logout()">退出</div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      title="登录"
      :visible.sync="dialogFormVisible"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form ref="ruleForm" :model="form" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            ref="password"
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            name="password"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <div v-if="!isClickCode" style="float: left; color: red">{{ time }}</div>
      <div v-if="wrongTimes > 0 && wrongTimes < 3" style="float: left; color: red">{{ `登陆失败${3 - wrongTimes}次后将锁定5分钟` }}</div>
      <div v-if="isClickCode && wrongTimes >= 3" style="float: left; color: red">{{ `登陆失败1次后将锁定5分钟` }}</div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          :disabled="!isClickCode"
          type="primary"
          @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { encryptAES, decryptAES } from '@/utils/cipher'
import { mapGetters } from 'vuex'
import { getMenu } from '@/api/menu' //api接口
import { setToken } from '@/utils/auth'
// import countdown from '../components/countdown.vue'
import { number } from 'echarts'
// import store from '@/store'

export default {
  name: 'pageHeader',
  data() {
    return {
      navList: [
        {
          path: '/',
          label: '首页'
        },
        {
          path: '/productIntroduction',
          label: '通用功能'
        },
        {
          path: '/dataSource',
          label: '开放数据'
        },
        // {
        //   path: "/dataService",
        //   label: "数据服务",
        // },
        {
          path: '/openPlatform',
          label: '开放平台'
        },
        {
          path: '/demand',
          label: '需求大厅'
        },
        {
          path: '/usageStatistics',
          label: '使用统计'
        }
        // {
        //   path: '/setting',
        //   label: '配置场景产品'
        // }
      ],
      dialogFormVisible: false,
      userInfo: '',
      form: {
        username: '',
        password: ''
      },
      time: '',
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ]
      },
      isClickCode: true,
      flag: false,
      wrongTimes: 0,
      // endTime: Number(localStorage.getItem('endTime'))
      // endTime: new Date().getTime() + 10 * 1000
    }
  },
  components: {
    // countdown
  },
  props: {
    bgColor: String,
    active: {
      type: Number,
      default: 0
    }
  },
  computed: {
    // 获取状态管路设置的值
    ...mapGetters(['isLogin'])
  },

  created() {
    // 获取返回的用户信息
    this.userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
    if (this.userInfo) {
      this.$store.dispatch('user/isLogin', true)
      setToken(this.userInfo.token) //设置缓存
    }
  },
  mounted() {
    // 集成页登陆后进入免登
    const query = decodeURIComponent(this.$route.query.params)
    const arr = decryptAES(query).split('&')
    // console.log('121212', arr);
    this.form.username = arr[0].split('=')[1]
    if (arr.length > 1) {
      this.form.password = arr[1].split('=')[1]
    }
    // this.$store
    //   .dispatch('user/login', this.form)
    //   .then((res) => {
    //     this.userInfo = res
    //   })
    //   .catch(() => {})
  },

  methods: {
    goPage(path) {
      this.$router.push(path)
    },
    timeDown() {
      const endTime = new Date(Number(localStorage.getItem('endTime')))
      const nowTime = new Date()
      let leftTime = parseInt((endTime.getTime() - nowTime.getTime()) / 1000)
      // let d = parseInt(leftTime / (24 * 60 * 60))
      // let h = this.formate(parseInt((leftTime / (60 * 60)) % 24))
      let m = this.formate(parseInt((leftTime / 60) % 60))
      let s = this.formate(parseInt(leftTime % 60))
      if (leftTime <= 0) {
        this.flag = true
        this.$emit('changeStatus', true)
        this.time = '请重新登录'
        this.isClickCode = true
      } else {
        console.log('倒计时', leftTime)
        this.time = `${m}分 ${s}秒后可重新登录`
        // this.time = `${d} 天 ${h} 小时 ${m} 分 ${s} 秒` // 需要修改时间样式的话 ，比如需要什么30分钟倒计时，就只保留分和秒
      }
    },
    formate(time) {
      if (time >= 10) {
        return time
      } else {
        return `0${time}`
      }
    },
    checkLogin() {
      this.wrongTimes = Number(localStorage.getItem('wrongPawd'))
      if (Number(localStorage.getItem('wrongPawd')) >= 2) {
        this.isClickCode = false
        if (
          parseInt(
            (new Date(Number(localStorage.getItem('endTime'))).getTime() -
              new Date().getTime()) /
              1000
          ) <= 0
        ) {
          this.isClickCode = true
        } else {
          // console.log('执行');
          this.isClickCode = false
          let time = setInterval(() => {
            if (this.flag == true) {
              clearInterval(time)
            }
            this.timeDown()
          }, 500)
        }
      }
    },
    //登录
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // const encryption = new AesEncryption({ key: 'Mw7DJgHqUZFAamxf8pXPjs28aBX1Ko8X' });
          this.form.password = encryptAES(this.form.password)
          this.$store
            .dispatch('user/login', this.form)
            .then((res) => {
              this.$message({
                message: '登录成功',
                type: 'success'
              })
              this.dialogFormVisible = false
              this.userInfo = res
            })
            .catch(() => {})
        } else {
          console.log('error submit!!')
          return false
        }
        setTimeout(() => {
          this.checkLogin()
        }, 1000)
      })
    },

    // 退出
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push('/')
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.header {
  .fix-top {
    background: rgba(41, 44, 77, 0.5);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 70px;
    z-index: 110;

    .top-bg {
      display: flex;
      justify-content: space-between;
      width: 1314px;
      margin: 0 auto;
    }

    .left-box {
      display: flex;
      flex: 1;

      .logo {
        display: flex;
        align-items: center;

        .name {
          color: #fff;
          margin-left: 10px;
          font-size: 20px;
          font-weight: 600;
          font-family: sHans, Microsoft YaHei;
        }
      }

      .nav {
        display: flex;
        align-items: center;
        margin-left: 20px;

        li {
          color: #fff;
          font-size: 16px;
          padding: 25px;
          cursor: pointer;

          &:hover {
            background: rgba(255, 255, 255, 0.2);
            border-bottom: 3px solid #fff;
            transition: background-color 0.2s ease-in-out;
          }
        }

        .active {
          background: rgba(255, 255, 255, 0.2);
          border-bottom: 3px solid #fff;
          transition: background-color 0.2s ease-in-out;
        }
      }
    }

    .login-box {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #fff;
    }
  }
}
</style>
